//
//  YH_NewsDetailViewController.m
//  YinHang
//
//  Created by 123 on 14-7-23.
//  Copyright (c) 2014年 iMobile. All rights reserved.
//

#import "YH_NewsDetailViewController.h"

#define kSCREEN_WIDTH [UIScreen mainScreen].applicationFrame.size.width

static NSInteger tag_for_indicator = 20140611;

@interface YH_NewsDetailViewController ()<UIImagePickerControllerDelegate, UINavigationControllerDelegate>
{
    NSMutableArray *_picArr; //图片数组
    
    ASIFormDataRequest *newsDetailRequest;//新闻详情请求
    
    MBProgressHUD *loadHud;
    
    NSCache *cellCache;
    
    NSString *html;//新闻详情字符串
    
    NSString *moviePath;//视频路径
}

@property (nonatomic, strong) NSURL *lastActionLink;

@property (nonatomic, strong) NSURL *baseURL;

@end

@implementation YH_NewsDetailViewController

/**
 为了保证内部不泄露，在dealloc中释放占用的内存
 */
- (void)dealloc
{
    [newsDetailRequest cancel];
    loadHud = nil;
    NSLog(@"HY_NewsDetailViewController dealloc...");
}

#pragma mark - 初始化

- (id)initWithNibName:(NSString *)nibNameOrNil bundle:(NSBundle *)nibBundleOrNil
{
    self = [super initWithNibName:nibNameOrNil bundle:nibBundleOrNil];
    if (self) {
        // Custom initialization
    }
    return self;
}

- (void)viewDidLoad
{
    [super viewDidLoad];
    // Do any additional setup after loading the view from its nib.
    self.navigationItem.title = @"引航网";
    [self customLeftBarButtonItem];
    
    // 适配屏幕
    _tableView.frame = self.view.frame;
    _reloadBtn.frame = self.view.frame;
    
    // 请求新闻详情
    [self queryNewsDetail];
    
    _picArr = [NSMutableArray array];
}

// 请求新闻详情
- (void)queryNewsDetail {
    // 检查网络
    if (![Constants isExistenceNetwork]) {
        _reloadBtn.hidden = NO;
        [self.view bringSubviewToFront:_reloadBtn];
        
    } else {
        // 提示正在加载数据...
        loadHud = [MBProgressHUD showHUDAddedTo:self.view animated:YES];
        loadHud.labelText = @"正在加载数据，请稍后...";
        
        /* 请求新闻详情 */
        newsDetailRequest = [ASIFormDataRequest requestWithURL:[NSURL URLWithString:API_STR]];
        newsDetailRequest.requestMethod = @"POST";
        // 设置超时时间
        newsDetailRequest.timeOutSeconds = 60;
        newsDetailRequest.delegate = self;
        // 设置参数
        NSString *action;
        switch (_selectedIndex) {
            case 0://新闻
                action = @"newsmain";
                break;
            case 1://人才
                action = @"zhaopinmain";
                break;
            case 2://视频
                action = @"videosmain";
                break;
            case 3://产品
                action = @"prosmain";
                break;
            case 4://图片
                action = @"casesmain";
                break;
            case 5://服务
                action = @"serinformain";
                break;
            default:
                break;
        }
        NSDictionary *paramsDict =  @{@"id": self.newsId};
        NSString *paramsStr = [NSString JSONString:paramsDict];
        NSString *result = [NSString stringWithFormat:TEMPLATE_PARAMSTR, action,paramsStr];
        
        NSData *paramsData = [result toGBKEncodingData];
        newsDetailRequest.postBody = [paramsData mutableCopy];
        
        [newsDetailRequest startAsynchronous];
    }
}

// 重新加载
- (IBAction)reloadNewsDetail:(id)sender {
    [self queryNewsDetail];
}

// 自定义LeftBarButtonItem
- (void)customLeftBarButtonItem {
    
    UIButton *leftBtn = [[UIButton alloc]initWithFrame:CGRectMake(0, 0, 20, 30)];
    [leftBtn setBackgroundImage:[UIImage imageNamed:@"back"] forState:UIControlStateNormal];
    [leftBtn addTarget:self action:@selector(back) forControlEvents:UIControlEventTouchUpInside];
    
    UIBarButtonItem *leftBarButtonItem = [[UIBarButtonItem alloc]initWithCustomView:leftBtn];
    UIBarButtonItem *negativeSpacer = [[UIBarButtonItem alloc] initWithBarButtonSystemItem:UIBarButtonSystemItemFixedSpace target:nil action:nil];
    negativeSpacer.width = - 10;
    if (ios7) {
        self.navigationItem.leftBarButtonItems = @[negativeSpacer,leftBarButtonItem];
    }else{
        self.navigationItem.leftBarButtonItems = @[leftBarButtonItem];
    }
}

#pragma mark - ASIHttpRequestDelegate method

- (void)requestFinished:(ASIHTTPRequest *)request {
    NSLog(@"%@",request.responseString);
    
    // 去除两端空格和回车
    NSString *responeStr = [request.responseString stringByTrimmingCharactersInSet:[NSCharacterSet whitespaceAndNewlineCharacterSet ]];
    //responeStr = [responeStr stringByReplacingOccurrencesOfString:@"\"" withString:@"\\\""];
    //NSLog(@"%@",responeStr);
    
    //responeStr = [responeStr stringByReplacingOccurrencesOfString:@"\r" withString:@""];
    // 去除tab(\t)
    //responeStr = [responeStr stringByReplacingOccurrencesOfString:@"\t" withString:@""];
    //NSLog(@"%@",responeStr);
    NSError *err;
    NSDictionary *result = [NSJSONSerialization JSONObjectWithData:[responeStr dataForUTF8] options:NSJSONReadingAllowFragments error:&err];
    
    // 1. 是否解析有错误
    if (!err) {
        
        // 2. 判断错误码
        NSInteger errorCode = [result[@"errorCode"]integerValue];
        if (errorCode == 0) {
            // 2.1 获取"info"
            NSDictionary *info = result[@"info"];
            
            NSString *readmePath = [[NSBundle mainBundle] pathForResource:@"IC_NewsDetailTemplate.html" ofType:nil];
            NSString *html_ = [NSString stringWithContentsOfFile:readmePath encoding:NSUTF8StringEncoding error:NULL];
            
            NSString *newsTitle = info[@"Title"];
            //NSString *author = info[@"Uid"];
            
            // 图片路径
          //***10.18***//
            // NSString *imgPath = [NSString stringWithFormat:@"%@%@",URL_DOMAIN,info[@"Picture"]];
            NSString *imgPath = [NSString stringWithFormat:@"%@",info[@"Picture"]];
            
            NSString *updateTime = info[@"Time"];
            //NSString *dateLine = [IMB_ConvertTimeStamp convertTimeStamp:updateTime dateFormat:@"yyyy-MM-dd  HH:mm"];
            
            NSString *newsContent;
            if (_selectedIndex == 2) {//视频路径
                moviePath = [NSString stringWithFormat:@"%@",info[@"Content"]];
                
                html = [NSString stringWithFormat:html_,20,newsTitle,@"未知",@"未知",updateTime,imgPath,@""];
                //改
                //html = [NSString stringWithFormat:newsTitle,@"未知",@"未知",updateTime,imgPath,@""];
                
            } else {//新闻内容
                newsContent  = info[@"Content"];
                
                html = [NSString stringWithFormat:html_,20,newsTitle,@"未知",@"未知",updateTime,imgPath,newsContent];
                //改
                //html = [NSString stringWithFormat:newsTitle,@"未知",@"未知",updateTime,imgPath,@""];
            }
            
            html = [html stringByReplacingOccurrencesOfRegex:REG_EXPR_FOR_HR_FOR_TAG withString:@"<br/>"];
            
            // add by jason yan 2014-06-04（添加过滤iframe）
            html = [html stringByReplacingOccurrencesOfRegex:REG_EXPR_FOR_IFRAME_FOR_TAG withString:@""];
            
            // 处理图片标签
            html = [html processImageTag];
            
            
            NSLog(@"%@",html);
            
            _reloadBtn.hidden = YES;
            [self.view sendSubviewToBack:_reloadBtn];
            
            [loadHud hide:YES];
            // 刷新数据
            [_tableView reloadData];
            
        } else {
            _reloadBtn.hidden = NO;
            [self.view bringSubviewToFront:_reloadBtn];
            
            [loadHud hide:YES];
            
            [SVProgressHUD showErrorWithStatus:result[@"errorMsg"]];
        }
        
    } else {
        _reloadBtn.hidden = NO;
        [self.view bringSubviewToFront:_reloadBtn];
        
        [loadHud hide:YES];
        
        [SVProgressHUD showErrorWithStatus:@"数据解析出错"];
    }
}

- (void)requestFailed:(ASIHTTPRequest *)request{
    _reloadBtn.hidden = NO;
    [self.view bringSubviewToFront:_reloadBtn];
    
    [loadHud hide:YES afterDelay:1];
    
    [SVProgressHUD showErrorWithStatus:@"服务器无法访问，请稍后再试!"];
}

- (void)didReceiveMemoryWarning
{
    [super didReceiveMemoryWarning];
    // Dispose of any resources that can be recreated.
}

#pragma mark - UITableViewDataSource

- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section {
    return 1;
}

- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath
{
    DTAttributedTextCell *cell_ = (DTAttributedTextCell *)[self tableView:tableView preparedCellForIndexPath:indexPath];
        
    return cell_;
}


#pragma mark DTCoreText Method
//################################## DTCoreText #####################################

- (void)configureCell:(DTAttributedTextCell *)cell forIndexPath:(NSIndexPath *)indexPath
{
    //[cell setHTMLString:html];
    [cell setHTMLString:html options:[self gainThemeOptions:cell]];
    
    cell.selectionStyle = UITableViewCellSelectionStyleNone;
    cell.attributedTextContextView.shouldDrawImages = YES;
}

- (DTAttributedTextCell *)tableView:(UITableView *)tableView preparedCellForIndexPath:(NSIndexPath *)indexPath
{
    static NSString *cellIdentifier = @"dtCellIdentifier";
    
    if (!cellCache)
    {
        cellCache = [[NSCache alloc] init];
    }
    
    // workaround for iOS  bug
    NSString *key = [NSString stringWithFormat:@"%ld-%ld", (long)indexPath.section, (long)indexPath.row];
    
    DTAttributedTextCell *cell = [cellCache objectForKey:key];
    
//    if (!cell)
//    {
        // reuse does not work for variable height
        //cell = (DTAttributedTextCell *)[tableView dequeueReusableCellWithIdentifier:cellIdentifier];
        
        if (!cell)
        {
            //用代码创建cell
            //cell = [[DTAttributedTextCell alloc] initWithReuseIdentifier:cellIdentifier accessoryType:UITableViewCellAccessoryDisclosureIndicator];
            cell = [[DTAttributedTextCell alloc] initWithReuseIdentifier:cellIdentifier];
            cell.attributedTextContextView.edgeInsets = UIEdgeInsetsMake(0, 10, 20, 10);
            cell.attributedTextContextView.delegate = self;
            
            _picArr = nil;
            _picArr = [[NSMutableArray alloc]init];
        }
        
        // cache it
        [cellCache setObject:cell forKey:key];
//    }
    
    [self configureCell:cell forIndexPath:indexPath];
    
    return cell;
}


#pragma mark 根据主题获取options(设置DTCoreText中字体大小跟颜色)

- (NSDictionary *)gainThemeOptions:(DTAttributedTextCell *)cell
{
    //设置字体颜色
    NSString *textColor = @"black";
    //设置字体
    NSString *textFont = @"17";
    
    CGSize maxImageSize = CGSizeMake(kSCREEN_WIDTH - 20.0, MAXFLOAT);
    
    
    NSMutableDictionary *options = [NSMutableDictionary dictionaryWithObjectsAndKeys:[NSNumber numberWithFloat:1.0],NSTextSizeMultiplierDocumentOption, [NSValue valueWithCGSize:maxImageSize],DTMaxImageSize, @"Hiragino Sans GB",DTDefaultFontFamily, textFont,DTDefaultFontSize, @"red",DTDefaultLinkColor, @"blue",DTDefaultLinkHighlightColor, textColor,DTDefaultTextColor,[NSNumber numberWithFloat:1.5f],DTDefaultLineHeightMultiplier,nil];
    
    //[NSNumber numberWithFloat:200],DTAttachmentParagraphSpacingAttribute,
    return options;
}




// disable this method to get static height = better performance
- (CGFloat)tableView:(UITableView *)tableView heightForRowAtIndexPath:(NSIndexPath *)indexPath
{
    if (indexPath.row == 0) {
        DTAttributedTextCell *cell = (DTAttributedTextCell *)[self tableView:tableView preparedCellForIndexPath:indexPath];
        
        return [cell requiredRowHeightInTableView:tableView];
    }
    CGFloat rowHeight = [self tableView:tableView cellForRowAtIndexPath:indexPath].bounds.size.height;
        
    return rowHeight;
}

#pragma mark Custom Views on Text

- (UIView *)attributedTextContentView:(DTAttributedTextContentView *)attributedTextContentView viewForAttributedString:(NSAttributedString *)string frame:(CGRect)frame
{
	NSDictionary *attributes = [string attributesAtIndex:0 effectiveRange:NULL];
	
	NSURL *URL = [attributes objectForKey:DTLinkAttribute];
	NSString *identifier = [attributes objectForKey:DTGUIDAttribute];
	
	
	DTLinkButton *button = [[DTLinkButton alloc] initWithFrame:frame];
	button.URL = URL;
	button.minimumHitSize = CGSizeMake(25, 25); // adjusts it's bounds so that button is always large enough
	button.GUID = identifier;
	
	// get image with normal link text
	UIImage *normalImage = [attributedTextContentView contentImageWithBounds:frame options:DTCoreTextLayoutFrameDrawingDefault];
	[button setImage:normalImage forState:UIControlStateNormal];
	
	// get image for highlighted link text
	UIImage *highlightImage = [attributedTextContentView contentImageWithBounds:frame options:DTCoreTextLayoutFrameDrawingDrawLinksHighlighted];
	[button setImage:highlightImage forState:UIControlStateHighlighted];
	
	// use normal push action for opening URL
	[button addTarget:self action:@selector(linkPushed:) forControlEvents:UIControlEventTouchUpInside];
	
	// demonstrate combination with long press
	UILongPressGestureRecognizer *longPress = [[UILongPressGestureRecognizer alloc] initWithTarget:self action:@selector(linkLongPressed:)];
	[button addGestureRecognizer:longPress];
	
	return button;
}


//加载图片
- (UIView*)attributedTextContentView:(DTAttributedTextContentView *)attributedTextContentView viewForAttachment:(DTTextAttachment *)attachment frame:(CGRect)frame{
    
    if ([attachment isKindOfClass:[DTImageTextAttachment class]]) {
        
        IMB_DownImageView *imageView = [[IMB_DownImageView alloc]initWithFrame:frame];
        imageView.backgroundColor = [UIColor redColor];
        imageView.imgURL = attachment.contentURL;
        imageView.contentMode = UIViewContentModeScaleAspectFit;
        [IMB_DownImageHelper downImageWithURL:attachment.contentURL imageView:imageView placeHolder:PLACE_HODER_IMG];
        
        
        
        /*DTLazyImageView *imageView = [[DTLazyImageView alloc] initWithFrame:frame];
         // add by jason yan
         imageView.contentMode = UIViewContentModeScaleAspectFit;
         imageView.url = attachment.contentURL;
         imageView.delegate = self;
         imageView.shouldShowProgressiveDownload = YES;*/
        
        // add by gcz 14.6.4 给图片添加链接
        // if there is a hyperlink then add a link button on top of this image
		if (attachment.hyperLinkURL)
		{
			// NOTE: this is a hack, you probably want to use your own image view and touch handling
			// also, this treats an image with a hyperlink by itself because we don't have the GUID of the link parts
			imageView.userInteractionEnabled = YES;
			
			DTLinkButton *button = [[DTLinkButton alloc] initWithFrame:imageView.bounds];
			button.URL = attachment.hyperLinkURL;
			button.minimumHitSize = CGSizeMake(25, 25); // adjusts it's bounds so that button is always large enough
			button.GUID = attachment.hyperLinkGUID;
			
			// use normal push action for opening URL
			[button addTarget:self action:@selector(linkPushed:) forControlEvents:UIControlEventTouchUpInside];
			
			// demonstrate combination with long press
			UILongPressGestureRecognizer *longPress = [[UILongPressGestureRecognizer alloc] initWithTarget:self action:@selector(linkLongPressed:)];
			[button addGestureRecognizer:longPress];
			
			[imageView addSubview:button];
		}

        
        
        imageView.userInteractionEnabled = YES;
        [imageView setBackgroundColor:[UIColor clearColor]];
        
        UITapGestureRecognizer *tapGR = [[UITapGestureRecognizer alloc]initWithTarget:self action:@selector(clickPic:)];
        [imageView addGestureRecognizer:tapGR];
        
        [imageView setLzTag:(_picArr.count)];
        [_picArr addObject:imageView.imgURL];
        
        return imageView;
    }
    return nil;
    
}
//DTCoreText画完回调 仅回调一次哦 不错吧~~
- (void)attributedTextContentView:(DTAttributedTextContentView *)attributedTextContentView didDrawLayoutFrame:(DTCoreTextLayoutFrame *)layoutFrame inContext:(CGContextRef)context
{
    UIActivityIndicatorView *indicator = (UIActivityIndicatorView *)[_tableView viewWithTag:tag_for_indicator];
    if ([indicator isKindOfClass:[UIActivityIndicatorView class]] && indicator.isAnimating ) {
        [indicator stopAnimating];
    }
}


#pragma mark - Actions

- (void)clickPic:(UITapGestureRecognizer *)recognizer
{
    if (_selectedIndex == 2) {
        // 播放视频
        MPMoviePlayerViewController *pvc = [[MPMoviePlayerViewController alloc]initWithContentURL:[NSURL URLWithString:moviePath]];
        [self presentMoviePlayerViewControllerAnimated:pvc];
        [pvc.moviePlayer play];
        
    } else {
        IMB_DownImageView *lzImgV = (IMB_DownImageView *)recognizer.view;
        //[self showImageURL:urlToSave point:pt];
        
        NSInteger count = _picArr.count;
        
        // 1.封装图片数据
        NSMutableArray *photos = [NSMutableArray arrayWithCapacity:count];
        for (int i = 0; i<count; i++) {
            // 替换为中等尺寸图片
            //NSString *url = _urls[i];
            MJPhoto *photo = [[MJPhoto alloc] init];
            photo.url = _picArr[i]; // 图片路径
            
            __block IMB_DownImageView *sourceImg;
            
            [lzImgV.superview.subviews enumerateObjectsUsingBlock:^(id obj, NSUInteger idx, BOOL *stop) {
                sourceImg = obj;
                if ([sourceImg isKindOfClass:[IMB_DownImageView class]] && sourceImg.lzTag == (i)) {
                    *stop = YES;
                    photo.srcImageView = sourceImg; // 来源于哪个UIImageView
                }
            }];
            
            if (!photo.srcImageView) {
                photo.srcImageView = lzImgV; //若找不到匹配的sdTag 则设置为点击的view
            }
            
            [photos addObject:photo];
        }
        
        // 2.显示相册
        MJPhotoBrowser *browser = [[MJPhotoBrowser alloc] init];
        
        __block NSInteger lzTag = 0;
        [_picArr enumerateObjectsUsingBlock:^(id obj, NSUInteger idx, BOOL *stop) {
            if (obj == lzImgV.imgURL) {
                lzTag = idx;
                *stop = YES;
            }
        }];
        
        browser.currentPhotoIndex = lzTag; // 弹出相册时显示的第一张图片是？
        browser.photos = photos; // 设置所有的图片
        [browser show];
    }
}

- (void)linkPushed:(DTLinkButton *)button
{
	NSURL *URL = button.URL;
	
	if ([[UIApplication sharedApplication] canOpenURL:[URL absoluteURL]])
	{
		[[UIApplication sharedApplication] openURL:[URL absoluteURL]];
	}
	else
	{
		if (![URL host] && ![URL path])
		{
            
			// possibly a local anchor link
			NSString *fragment = [URL fragment];
			
			if (fragment)
			{
				//[_textView scrollToAnchorNamed:fragment animated:NO];
			}
		}
	}
}


- (void)actionSheet:(UIActionSheet *)actionSheet clickedButtonAtIndex:(NSInteger)buttonIndex
{
	if (buttonIndex != actionSheet.cancelButtonIndex)
	{
		[[UIApplication sharedApplication] openURL:[self.lastActionLink absoluteURL]];
	}
}

- (void)linkLongPressed:(UILongPressGestureRecognizer *)gesture
{
	if (gesture.state == UIGestureRecognizerStateBegan)
	{
		DTLinkButton *button = (id)[gesture view];
		button.highlighted = NO;
		self.lastActionLink = button.URL;
		
		if ([[UIApplication sharedApplication] canOpenURL:[button.URL absoluteURL]])
		{
			UIActionSheet *action = [[UIActionSheet alloc] initWithTitle:[[button.URL absoluteURL] description] delegate:self cancelButtonTitle:@"取消" destructiveButtonTitle:nil otherButtonTitles:@"用Safari打开", nil];
			[action showFromRect:button.frame inView:button.superview animated:YES];
		}
	}
}



#pragma mark DTLazyImageViewDelegate

- (void)lazyImageView:(DTLazyImageView *)lazyImageView didChangeImageSize:(CGSize)size {
    
    DTAttributedTextCell *picTextCell = [self tableView:_tableView preparedCellForIndexPath:[NSIndexPath indexPathForItem:0 inSection:0]];
    
    lazyImageView.userInteractionEnabled = YES;
    NSURL *url = lazyImageView.url;
	NSPredicate *pred = [NSPredicate predicateWithFormat:@"contentURL == %@", url];
	BOOL didUpdate = NO;
    for (DTTextAttachment *oneAttachment in [picTextCell.attributedTextContextView.layoutFrame textAttachmentsWithPredicate:pred])
	{
        
        if (CGSizeEqualToSize(oneAttachment.originalSize, CGSizeZero))
		{
            if (size.width > 300) {
                oneAttachment.originalSize = CGSizeMake(300, size.height/(size.width/300));
                
            }else{
                oneAttachment.originalSize = size;
            }
            
            didUpdate = YES;
			
 		}
        
        
        if (didUpdate) {
            
            [picTextCell performSelectorInBackground:@selector(relayoutText) withObject:nil];
            //[picTextCell.attributedTextContextView performSelector:@selector(relayoutText) withObject:nil afterDelay:0.1f];
            [_tableView performSelector:@selector(reloadData) withObject:nil afterDelay:.1f];
            
        }else{
            [lazyImageView sd_cancelCurrentImageLoad];
            [lazyImageView cancelLoading];
            //[lazyImageView cancelCurrentArrayLoad];
            
            lazyImageView.delegate = nil;
        }
    }
}

// 返回
- (void)back {
    [newsDetailRequest cancel];
    [self.navigationController popViewControllerAnimated:YES];
}

@end
